// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace SnapObjects.Data
{
    internal class XmlUnPackerParser<T> : IDataUnpackerParser<T>
    {
        public T Parse(string value)
        {
            return (T)XmlDeserialize.Deserialize(value, typeof(T));
        }
    }

    internal class XmlUnPackerParser : IDataUnpackerParser
    {
        private readonly Type _dataType;

        public XmlUnPackerParser(Type dataType)
        {
            _dataType = dataType;
        }

        public object Parse(string value)
        {
            return XmlDeserialize.Deserialize(value, _dataType);
        }
    }

    internal class XmlDeserialize
    {
        public static object Deserialize(string xml, Type dataType)
        {
            object model;
            var settings = new XmlReaderSettings
            {
                IgnoreComments = true,
                IgnoreWhitespace = true,
                IgnoreProcessingInstructions = true
            };

            using (var xmlReader = XmlReader.Create(new StringReader(xml), settings))
            {
                var serializer = new XmlSerializer(dataType);
                model = serializer.Deserialize(xmlReader);
            }

            return model;
        }
    }
}
